import { Component, Host } from "@angular/core";
import { AuthenticationService } from "../login.service";
import { ActivatedRoute } from "@angular/router";
import { AppComponent } from "../../../app.component";

/**
 * TODO: 'temp' parameter no longer used by the new UI.
 */
@Component({
    templateUrl: 'changePass.component.html',
    styleUrls: ['changePass.component.scss', '../login.component.scss']
})
export class ChangePassComponent {
    public conditions: any[] = [
        {
            text: 'Must be at least 7 characters long',
            valid: false,
            method: _ => {
                return this.password && this.password.length >= 7;
            }
        },
        {
            text: 'Must contain at least 1 capital letter',
            valid: false,
            method: _ => {
                var regexp = /(?=.*[A-Z])/;
                return regexp.test(this.password);
            }
        },
        {
            text: 'Must contain at least 1 number',
            valid: false,
            method: _ => {
                var regexp = /(?=.*[0-9])/;
                return regexp.test(this.password);
            }
        },
        {
            text: 'Invalid characters (", &, \', <, >, +, {, })',
            valid: false,
            method: _ => {
                var regexp = /(^.*?(?=[&'"<>+{}]).*$)/;
                return !regexp.test(this.password);
            }
        },
        {
            text: 'The passwords do not match',
            valid: false,
            method: _ => {
                return this.password && this.password == this.confirm;
            }
        }
    ];
    public valid: boolean = false;
    public reset: boolean = false;
    public sent: boolean = false;
    public password: string;
    public confirm: string;    

    private email: string;

    constructor(
        private route: ActivatedRoute,
        @Host() private rootComponent: AppComponent,
        private authService: AuthenticationService) { }

    ngOnInit() {
        this.route.params.subscribe(param => {
            //get email and temp pass
            this.email = param['email'];
            this.rootComponent.finishLoading();
        });
    }

    public conditionValid(index: number): boolean {
        this.conditions[index].valid = this.conditions[index].method();
        this.valid = this.conditions.findIndex(x => x.valid == false) == -1;
        return this.conditions[index].valid;
    }

    public changePass() {
        this.sent = true;
        this.authService.changePassword(this.email, this.password).subscribe(_ => {
            this.reset = true;
        });
    }
}